#include "stdafx.h"
#include "util/backgroundprocessor.h"

namespace natrium {
	namespace util {
		BackgroundProcessor::BackgroundProcessor():
			mDone(false)
		{
			for (unsigned int i = 0; i < std::thread::hardware_concurrency(); ++i)
				mWorkers.emplace_back(std::thread([this] {
					while (!mDone)
						mWork.pop()();
				}));
		}

		BackgroundProcessor::~BackgroundProcessor() {
			for (size_t i = 0; i < mWorkers.size(); ++i)
				mWork.push([this] { mDone = true; }); //trigger all of the workers
		
			for (auto& worker: mWorkers)
				worker.join();
		}

		void BackgroundProcessor::operator()(const std::function<void()>& work) {
			mWork.push(work);
		}

		void BackgroundProcessor::addWork(const std::function<void()>& work) {
			mWork.push(work);
		}
	}
}